# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/15'
__author__ = 'Just'
__filename__ = 'scope'
权限管理配置  [读取 配置文件或redis]
"""


class ScopeBase:
    # 权限基类
    allow_api = []              # 可访问的api
    forbidden_api = []          # 禁止访问的api
    allow_module = []           # 可访问的视图模块 包含 视图模块下的所有api

    def __add__(self, other):
        """运算符重载 __add__ = '+' """
        self.allow_api = self.allow_api + other.allow_api
        self.allow_api = list(set(self.allow_api))

        self.forbidden_api = self.forbidden_api + other.forbidden_api
        self.forbidden_api = list(set(self.forbidden_api))

        self.allow_module = self.allow_module + other.allow_module
        self.allow_module = list(set(self.allow_module))

        return self


class SuperAdminScope(ScopeBase):
    # 超级管理员权限
    allow_api = []
    forbidden_api = ['v1.user+delete_user', 'v1.comic+one']
    allow_module = ['cms.user', 'cms.banner', 'cms.theme', 'cms.comic',
                    'v1.user', 'v1.comic', 'v1.theme']


class AdminScope(ScopeBase):
    # 管理员权限
    allow_api = []
    forbidden_api = ['v1.user+delete_user']
    allow_module = []

    def __init__(self):
        self + SuperAdminScope()



class UserScope(ScopeBase):
    # 普通用户权限
    allow_api = ['v1.user+get_user', 'v1.user+revise_user']
    forbidden_api = []
    allow_module = []


def is_in_scope(scope, endpoint):
    """
    访问接口权限 判断
    :param scope: 权限类名str
    :param endpoint: 要访问的视图函数
    :return: Boolean
    """
    scope = globals()[scope]()  # globals()=> 字典 反射 类名str => 类
    endpoint_split = endpoint.split('+')    # 路由视图规则 已自定义

    endpoint_module = endpoint_split[0].strip()     # 视图模块

    if endpoint in scope.forbidden_api:
        return False
    if endpoint in scope.allow_api:
        return True
    if endpoint_module in scope.allow_module:
        return True
    else:
        return False
